package com.sunday.shoufen.ui;

import android.annotation.SuppressLint;
import android.content.Intent;
import android.graphics.Color;
import android.graphics.Paint;
import android.os.Bundle;

import android.os.Parcelable;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.bumptech.glide.Glide;
import com.sunday.common.adapter.CommenAdapter;
import com.sunday.common.adapter.ViewHolder;
import com.sunday.common.base.BaseActivity;
import com.sunday.common.model.ResultDO;
import com.sunday.common.utils.DeviceUtils;
import com.sunday.common.utils.PixUtils;
import com.sunday.common.utils.StatusBarUtil;
import com.sunday.common.utils.ToastUtils;
import com.sunday.common.widgets.CircleImageView;
import com.sunday.common.widgets.GradationScrollView;
import com.sunday.common.widgets.MyRatingBar;
import com.sunday.common.widgets.NoScrollGridView;
import com.sunday.common.widgets.NoScrollListview;
import com.sunday.common.widgets.banner.ConvenientBanner;
import com.sunday.common.widgets.banner.holder.ViewHolderCreator;
import com.sunday.shoufen.R;
import com.sunday.shoufen.adapter.BannerHolder;
import com.sunday.shoufen.adapter.ShopSetListAdapter;
import com.sunday.shoufen.base.BaseApp;
import com.sunday.shoufen.entity.BizShopSet;
import com.sunday.shoufen.entity.Comment;
import com.sunday.shoufen.entity.ShopDetail;
import com.sunday.shoufen.http.ApiClient;
import com.sunday.shoufen.ui.widgets.SelectMapWindow;

import java.util.ArrayList;
import java.util.List;

import butterknife.Bind;
import butterknife.ButterKnife;
import butterknife.OnClick;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;

/**
 * Created by 刘涛 on 2017/10/19.
 */

public class ShopDetailActivity extends BaseActivity {


    @Bind(R.id.banner)
    ConvenientBanner banner;
    @Bind(R.id.product_title)
    TextView productTitle;
    @Bind(R.id.rating_bar)
    MyRatingBar ratingBar;
    @Bind(R.id.rating_score)
    TextView ratingScore;
    @Bind(R.id.shop_addr)
    TextView shopAddr;
    @Bind(R.id.shop_open_time)
    TextView shopOpenTime;
    @Bind(R.id.shop_strategy1)
    TextView shopStrategy1;
    @Bind(R.id.shop_strategy2)
    TextView shopStrategy2;
    @Bind(R.id.shop_intro)
    TextView shopIntro;
    @Bind(R.id.shop_set_num)
    TextView shopSetNum;
    @Bind(R.id.list_view)
    NoScrollListview listView;
    @Bind(R.id.txt_check_more_set)
    TextView txtCheckMoreSet;
    @Bind(R.id.ll_check_more_set)
    LinearLayout llCheckMoreSet;
    @Bind(R.id.comment_rating_bar)
    MyRatingBar commentRatingBar;
    @Bind(R.id.comment_rating_score)
    TextView commentRatingScore;
    @Bind(R.id.comment_num)
    TextView commentNum;
    @Bind(R.id.scrollview)
    GradationScrollView scrollView;
    @Bind(R.id.btn_buy)
    TextView btnBuy;
    @Bind(R.id.bottom_layout)
    LinearLayout bottomLayout;
    @Bind(R.id.title_text)
    TextView titleText;
    @Bind(R.id.back)
    ImageView back;
    @Bind(R.id.btn_collect)
    ImageView btnCollect;
    @Bind(R.id.btn_share)
    ImageView btnShare;
    @Bind(R.id.title_layout)
    RelativeLayout titleLayout;


    @Bind(R.id.user_logo)
    CircleImageView userLogo;
    @Bind(R.id.user_name)
    TextView userName;
    @Bind(R.id.user_score)
    MyRatingBar userScore;
    @Bind(R.id.user_time)
    TextView userTime;
    @Bind(R.id.content)
    TextView content;
    @Bind(R.id.grid_view)
    NoScrollGridView gridView;
    @Bind(R.id.reply_content)
    TextView replyContent;
    @Bind(R.id.ll_reply)
    LinearLayout llReply;
    @Bind(R.id.rl_comment)
    RelativeLayout rlComment;

    private ShopDetail shopDetail;
    private long shopId;
    private long memberId;
    private String latitude, longitude;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_shop_detail);
        ButterKnife.bind(this);
        initView();
        getProductDetail();

    }

    private void initView() {
        memberId = BaseApp.getInstance().getMember().getId();
        latitude = BaseApp.getInstance().getLatitude();
        longitude = BaseApp.getInstance().getLongitude();
        titleText.setText("商品详情");
        scrollView.setScrollViewListener(new GradationScrollView.ScrollViewListener() {
            @Override
            public void onScrollChanged(GradationScrollView scrollView, int x, int y, int oldx, int oldy) {
                if (y < DeviceUtils.getDisplay(mContext).widthPixels - PixUtils.dip2px(mContext, 48) - StatusBarUtil.getStatusBarHeight(mContext)) {
                    titleLayout.setBackgroundColor(Color.parseColor("#00000000"));
                    titleText.setVisibility(View.GONE);
                    back.setImageResource(R.mipmap.return_white);
                } else {
                    titleLayout.setBackgroundColor(Color.parseColor("#ffffff"));
                    titleText.setVisibility(View.VISIBLE);
                    titleText.setTextColor(Color.parseColor("#333333"));
                    back.setImageResource(R.mipmap.ic_back);
                }
            }
        });
        shopId = getIntent().getLongExtra("shopId", 0);
    }

    private void getProductDetail() {
        showLoadingDialog(0);
        Call<ResultDO<ShopDetail>> call = ApiClient.getApiAdapter().getShopDetail(shopId, latitude, longitude, memberId);
        call.enqueue(new Callback<ResultDO<ShopDetail>>() {
            @Override
            public void onResponse(Call<ResultDO<ShopDetail>> call, Response<ResultDO<ShopDetail>> response) {
                if (isFinish || response.body() == null) {
                    return;
                }
                dissMissDialog();
                if (response.body().getCode() == 0) {
                    shopDetail = response.body().getResult();
                    updateView(shopDetail);
                }
            }

            @Override
            public void onFailure(Call<ResultDO<ShopDetail>> call, Throwable t) {
                dissMissDialog();
            }
        });

    }

    @SuppressLint("DefaultLocale")
    private void updateView(final ShopDetail shopDetail) {
        if (shopDetail == null) {
            return;
        }

        final List<String> bannerImgs = new ArrayList<>();
        if (shopDetail.getImages() != null && shopDetail.getImages().size() > 0) {
            bannerImgs.addAll(shopDetail.getImages());
        }
        banner.getLayoutParams().width = DeviceUtils.getDisplay(mContext).widthPixels;
        banner.getLayoutParams().height = DeviceUtils.getDisplay(mContext).widthPixels * 5 / 6;
        banner.startTurning(3000);
        banner.setFocusable(true);
        banner.setFocusableInTouchMode(true);
        banner.requestFocus();
        banner.setPages(new ViewHolderCreator<BannerHolder>() {
            @Override
            public BannerHolder createHolder() {
                return new BannerHolder();
            }
        }, bannerImgs)
                .setPageIndicator(new int[]{R.drawable.ic_page_indicator, R.drawable.ic_page_indicator_focused});
        banner.notifyDataSetChanged();

        productTitle.setText(shopDetail.getShopName());
        shopAddr.setText(shopDetail.getAddress());
        shopOpenTime.setText("营业时间:" + shopDetail.getBusinessTime());
        shopSetNum.setText("服务套餐");
        ratingBar.setRating((int) shopDetail.getScore(), R.drawable.rating_bar, false, 30);
        ratingScore.setText((int) shopDetail.getScore() + "分");
        if (shopDetail.getIsAddActive() == 1) {
            if (shopDetail.getCommissionScale() == 0) {
                shopStrategy1.setVisibility(View.GONE);
            }
            shopStrategy1.setText(new StringBuilder().append(String.format("赚消费积分%.2f", shopDetail.getCommissionScale())).append("%").toString());
            shopStrategy2.setText(new StringBuilder().append(String.format("领活动通用券%.2f", shopDetail.getCouponCommission())).append("%").toString());
        } else {
            shopStrategy2.setVisibility(View.GONE);
            shopStrategy1.setText(new StringBuilder().append(String.format("赚消费积分%.2f", shopDetail.getCommissionScale())).append("%").toString());
        }
        btnCollect.setSelected(shopDetail.isCollect());


        //套餐
        if (!shopDetail.getProductList().isEmpty()) {
            List<BizShopSet> proList = new ArrayList<>();
            if (shopDetail.getProductList().size() > 3) {
                proList.addAll(shopDetail.getProductList().subList(0, 3));
            } else {
                proList.addAll(shopDetail.getProductList());
            }
            listView.setAdapter(new CommenAdapter<BizShopSet>(mContext, proList, R.layout.list_shop_set_item) {
                @Override
                public void convert(ViewHolder helper, BizShopSet item, int position) {
                    ImageView proImg = helper.getView(R.id.shop_set_img);
                    TextView proName = helper.getView(R.id.shop_set_name);
                    TextView proPrice = helper.getView(R.id.price_now);
                    TextView proPriceOld = helper.getView(R.id.price_old);
                    TextView proSaleNum = helper.getView(R.id.sale_num);
                    Glide.with(mContext).load(item.getImage())
                            .error(R.mipmap.ic_default)
                            .into(proImg);
                    proName.setText(item.getProductName());
                    proPrice.setText("￥" + item.getPrice());
                    proPriceOld.setText("￥" + item.getMarketPrice());
                    proPriceOld.getPaint().setFlags(Paint.STRIKE_THRU_TEXT_FLAG | Paint.ANTI_ALIAS_FLAG);
                    proSaleNum.setText("已售" + item.getSaleCount());

                }
            });
            listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
                @Override
                public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                    intent = new Intent(mContext, ShopSetDetailActivity.class);
                    intent.putExtra("productId", shopDetail.getProductList().get(position).getProductId());
                    startActivity(intent);
                }
            });
        }

        //评论
        commentRatingBar.setRating((int) shopDetail.getScore(), R.drawable.rating_bar, false, 30);
        commentRatingScore.setText((int) shopDetail.getScore() + "分");
        commentNum.setText(shopDetail.getCommentCount() + "条评价");


        rlComment.setVisibility(!shopDetail.getCommentList().isEmpty() ? View.VISIBLE : View.GONE);
        final Comment item;
        if (!shopDetail.getCommentList().isEmpty()) {
            item = shopDetail.getCommentList().get(0);
            Glide.with(mContext)
                    .load(item.getLogo()).error(R.mipmap.ic_default).into(userLogo);
            userName.setText(item.getNickName());
            userScore.setRating((int) item.getScore(), R.drawable.rating_bar, false, 30);
            userTime.setText(item.getCreateTime());
            content.setText(item.getContent());
            if (item.getImages() != null && !item.getImages().isEmpty()) {
                gridView.setAdapter(new CommenAdapter<String>(mContext, item.getImages(), R.layout.list_comment_img_item) {
                    @Override
                    public void convert(com.sunday.common.adapter.ViewHolder helper, String item, int position) {
                        ImageView imgView = helper.getView(R.id.comment_img);
                        Glide.with(mContext)
                                .load(item)
                                .error(R.mipmap.ic_default)
                                .into(imgView);
                    }
                });
                gridView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
                    @Override
                    public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                        Intent intent = new Intent(mContext, ShowBigImage.class);
                        intent.putStringArrayListExtra("data", (ArrayList<String>) item.getImages());
                        intent.putExtra("index", position);
                        mContext.startActivity(intent);
                    }
                });
            }
            if (item.getReplay() != null && !item.getReplay().isEmpty()) {
                llReply.setVisibility(View.VISIBLE);
                replyContent.setText(item.getReplay().get(0).getContent());
            } else {
                llReply.setVisibility(View.GONE);
            }
        }


    }

    @OnClick({R.id.shop_intro, R.id.btn_buy, R.id.shop_set_num, R.id.check_more_comment, R.id.btn_share, R.id.btn_collect,
            R.id.shop_addr})
    void onClick(View v) {
        switch (v.getId()) {
            case R.id.shop_intro:
                intent = new Intent(mContext, ShopDescActivity.class);
                intent.putExtra("html", shopDetail.getDesc());
                intent.putExtra("shopId",shopDetail.getShopId());
                startActivity(intent);
                break;
            case R.id.btn_buy:
                intent = new Intent(mContext, ScanBuyActivity.class);
                intent.putExtra("shopDetail", shopDetail);
                startActivity(intent);
                break;
            case R.id.shop_set_num:
                //套餐列表
                if (!shopDetail.getProductList().isEmpty()) {
                    intent = new Intent(mContext, ShopSetListActivity.class);
                    intent.putExtra("sellerId", shopDetail.getShopId());
                    intent.putExtra("type", shopDetail.getIsAddActive());
                    startActivity(intent);
                }
                break;
            case R.id.check_more_comment:
                if (!shopDetail.getCommentList().isEmpty()) {
                    intent = new Intent(mContext, CommentListActivity.class);
                    intent.putExtra("sellerId", shopDetail.getShopId());
                    startActivity(intent);
                }
                break;
            case R.id.btn_share:
                //

                break;
            case R.id.btn_collect:
                //
                doCollect();
                break;
            case R.id.shop_addr:
                String desLatit = shopDetail.getLatitude();
                String desLongit = shopDetail.getLongitude();
                SelectMapWindow window = new SelectMapWindow(mContext, latitude, longitude, desLatit, desLongit);
                window.showPopupWindow(shopAddr);
                break;
        }
    }

    private void doCollect() {
        Call<ResultDO> call = ApiClient.getApiAdapter().doCollect(shopId, memberId, 3);
        call.enqueue(new Callback<ResultDO>() {
            @Override
            public void onResponse(Call<ResultDO> call, Response<ResultDO> response) {
                if (response.body() == null || isFinish) {
                    return;
                }
                if (response.body().getCode() == 0) {
                    btnCollect.setSelected(!btnCollect.isSelected());
                } else {
                    ToastUtils.showToast(mContext, response.body().getMessage());
                }

            }

            @Override
            public void onFailure(Call<ResultDO> call, Throwable t) {

            }
        });
    }

}
